<template>
  <mds-breadcrumb class="app-breadcrumb">
    <mds-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
      <span
        v-if="item.redirect === 'noRedirect' || index === levelList.length - 1"
        class="no-redirect"
      >
        {{ item.meta.title }}
      </span>
      <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
    </mds-breadcrumb-item>
  </mds-breadcrumb>
</template>

<script lang="ts">
import { Component, Watch } from 'vue-property-decorator'
import DefaultMixin from '@/mixins/DefaultMixin'
import * as pathToRegexp from 'path-to-regexp'

@Component({})
export default class extends DefaultMixin {
  private levelList = null

  @Watch('$route')
  private onRouteChange(route: any) {
    // if you go to the redirect page, do not update the breadcrumbs
    if (route.path.startsWith('/redirect/')) {
      return
    }
    this.getBreadcrumb()
  }

  created(): void {
    this.getBreadcrumb()
  }
  private getBreadcrumb() {
    // only show routes with meta.title
    let matched = this.$route.matched.filter((item: any) => item.meta && item.meta.title)
    const first = matched[0]
    if (!this.isProcess(first)) {
      matched = [{ path: '/', meta: { title: '首页' }, redirect: '/databoard/workbench' }].concat(
        matched,
      )
    }
    this.levelList = matched.filter(
      (item: any) => item.meta && item.meta.title && item.meta.breadcrumb !== false,
    )
  }
  private isProcess(route: any) {
    const name = route && route.name
    if (!name) {
      return false
    }
    return name.trim().toLocaleLowerCase() === 'process'.toLocaleLowerCase()
  }
  private pathCompile(path: string) {
    const { params } = this.$route
    const toPath = pathToRegexp.compile(path)
    return toPath(params)
  }
  private handleLink(item: any) {
    const { redirect, path } = item
    if (redirect && redirect === this.$route.path) {
      // 手动重定向页面到 '/redirect' 页面
      this.refreshPage()
      return
    }
    if (redirect) {
      this.$router.push(redirect)
      return
    }
    this.$router.push(this.pathCompile(path))
  }
}
</script>

<style lang="scss" scoped>
.app-breadcrumb.mds-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
